//
//  NSString+MJ.m
//  新浪微博
//
//  Created by apple on 13-10-27.
//  Copyright (c) 2013年 itcast. All rights reserved.
//

#import "NSString+DF.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (DF)


+ (instancetype)localizedStringWithDateSinceNow:(NSDate*)date {
//    NSDate *tmp = [NSDate date];
//    NSDate *currentDate = [tmp dateByAddingTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMTForDate:tmp]];
//    [currentDate compare:date];

    NSInteger  timeInterval = [@(-[date timeIntervalSinceNow]) integerValue];
    if(timeInterval<0) {
        return @"穿越";
    }else if(timeInterval==0) {
        return @"刚刚";
    }else if(timeInterval<60) {
        return [NSString stringWithFormat:@"%@秒前",@(timeInterval)];
    }else if(timeInterval/60<60) {
        return [NSString stringWithFormat:@"%@分钟前",@(timeInterval/60)];
    }else if(timeInterval/60/60<24) {
        return [NSString stringWithFormat:@"%@小时前",@(timeInterval/60/60)];
    }else  {
        return [NSString stringWithFormat:@"%@天前",@(timeInterval/60/60/24)];
    }
}

- (NSString *)fileAppend:(NSString *)append
{
    // 1.1.获得文件拓展名
    NSString *ext = [self pathExtension];
    
    // 1.2.删除最后面的扩展名
    NSString *imgName = [self stringByDeletingPathExtension];
    
    // 1.3.拼接-568h@2x
    imgName = [imgName stringByAppendingString:append];
    
    // 1.4.拼接扩展名
    return [imgName stringByAppendingPathExtension:ext];
}


-(id)json {
    NSError *error = nil;
    NSData* jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
    if(error) {
        NSLog(@"jsonWithEncoding:%@",error.localizedDescription);
    }
    return jsonObject;
}


-(NSString *)md5Hex {
    const char* str = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, strlen(str), result);
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02X",result[i]];
    }
    return ret;
}


-(BOOL)isEmpty {
    if ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}



#pragma mark 验证邮箱
- (BOOL)isEmail
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

+(NSString *)stringWithNumber:(NSNumber *)number {
    NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
    return [formatter stringFromNumber:number];
}


#pragma mark 清空字符串中的空白字符
- (NSString *)trimString
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

#pragma mark 返回沙盒中的文件路径
- (NSString *)documentsPath
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    return [path stringByAppendingString:self];
}

#pragma mark 写入系统偏好
- (void)saveToUserDefaults:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] setObject:self forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


#pragma mark 验证是否匹配正则表达式
-(BOOL)matchesWithPattern:(NSString*)pattern {
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    return [regex numberOfMatchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];
}



+ (NSString *)roundUpNumber:(float)number scale:(short)scale{
    return [self roundNumber:number scale:scale roundingMode:NSRoundUp];
}

+ (NSString *)roundDownNumber:(float)number scale:(short)scale{
    return [self roundNumber:number scale:scale roundingMode:NSRoundDown];
}


+ (NSString *)roundPlainNumber:(float)number scale:(short)scale{
    return [self roundNumber:number scale:scale roundingMode:NSRoundPlain];
}


+ (NSString *)roundBankersNumber:(float)number scale:(short)scale{
    return [self roundNumber:number scale:scale roundingMode:NSRoundBankers];
}

+ (NSString *)roundNumber:(float)number scale:(short)scale roundingMode:(NSRoundingMode)roundingMode {
    
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:roundingMode scale:scale raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    
    NSDecimalNumber *ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:number];
    
    NSDecimalNumber *roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    
    return [NSString stringWithFormat:@"%@",roundedOunces];
    
}


-(NSString *)encodeToPercentEscapeString {
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
}


-(NSString*)stringByFilterHtml {
    NSMutableString* tmp = [NSMutableString stringWithString:self];
    
    [[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>" options:NSRegularExpressionCaseInsensitive error:nil] replaceMatchesInString:tmp options:NSMatchingReportProgress range:NSMakeRange(0, tmp.length) withTemplate:@""];
    
    [[NSRegularExpression regularExpressionWithPattern:@"<!--.*-->" options:NSRegularExpressionCaseInsensitive error:nil] replaceMatchesInString:tmp options:NSMatchingReportProgress range:NSMakeRange(0, tmp.length) withTemplate:@""];

    
    [[NSRegularExpression regularExpressionWithPattern:@"&(quot|#34);" options:NSRegularExpressionCaseInsensitive error:nil] replaceMatchesInString:tmp options:NSMatchingReportProgress range:NSMakeRange(0, tmp.length) withTemplate:@"\\"];
    
    [[NSRegularExpression regularExpressionWithPattern:@"&(amp|#38);" options:NSRegularExpressionCaseInsensitive error:nil] replaceMatchesInString:tmp options:NSMatchingReportProgress range:NSMakeRange(0, tmp.length) withTemplate:@","];
    
    [[NSRegularExpression regularExpressionWithPattern:@"&(lt|#60);" options:NSRegularExpressionCaseInsensitive error:nil] replaceMatchesInString:tmp options:NSMatchingReportProgress range:NSMakeRange(0, tmp.length) withTemplate:@"<"];
    
    [[NSRegularExpression regularExpressionWithPattern:@"&(gt|#62);" options:NSRegularExpressionCaseInsensitive error:nil] replaceMatchesInString:tmp options:NSMatchingReportProgress range:NSMakeRange(0, tmp.length) withTemplate:@">"];
    
    [[NSRegularExpression regularExpressionWithPattern:@"&(nbsp|#160);" options:NSRegularExpressionCaseInsensitive error:nil] replaceMatchesInString:tmp options:NSMatchingReportProgress range:NSMakeRange(0, tmp.length) withTemplate:@" "];
    
    [[NSRegularExpression regularExpressionWithPattern:@"&(.*);" options:NSRegularExpressionCaseInsensitive error:nil] replaceMatchesInString:tmp options:NSMatchingReportProgress range:NSMakeRange(0, tmp.length) withTemplate:@""];
    
    return tmp;
}


+ (NSString *)sha1:(NSString *)str {
    const char *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:str.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (uint32_t)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}

- (NSString *)md5 {
    const char *cStr = [self?self:@"" UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (uint32_t)strlen(cStr), result );
    return [[NSString stringWithFormat:
             @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]] lowercaseString];
}

/**
 *  md5算法 得到指定的 后缀名 的文件名
 *
 *  @param extension 后最名，= nil 时，没有后缀
 *
 *  @return MD5文件名
 */
- (NSString *)fileNameMD5WithExtension:(NSString *)extension {
    if (extension && extension.length>0) {
        return [[self md5] stringByAppendingPathExtension:extension];
    }
    else {
        return [self md5];
    }
}


/**
 * 2015-10-20 13:58:40 转友好时间
 */
+ (NSString *)friendTimeWithTimeStr:(NSString *)theDate {
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *date=[formatter dateFromString:theDate];
    NSTimeInterval late = [date timeIntervalSince1970]*1;
    
    return [NSString stringByTimeInterval:late containTime:NO useChinese:YES];
}

/**
 * 与当前时间戳比较
 00 00:00:01 - 00 00:00:05：刚刚
 00 00:00:06 - 00 00:00:59：5-59 秒前
 
 00 00:01:00 - 00 00:59:59：1-59:59 分钟前
 
 00 01:00:00 - 00 23:59:59：1-23 小时前
 
 01 00:00:00 - 01 23:59:59：昨天
 02 00:00:00 - 06 23:59:59：2-6 天前
 
 07 00:00:00 - 28 00:00:00：1-4 星期前
 
 28 00:00:01 - ...：具体时间
 
 * @param containTime 是否包含时间
 * @return 间隔描述文本
 */

+ (NSString *)stringByTimeInterval:(NSTimeInterval)timeInterval containTime:(BOOL)containTime useChinese:(BOOL)useChinese {
    NSString *result = nil;
    NSInteger dis = [[NSDate date] timeIntervalSince1970]-timeInterval;
    
    while (YES) {
        if (dis <= 5) {
            result = (useChinese ? @"刚刚":@"a moment ago");
            break;
        }
        if (dis>=6 && dis<=59) {
            result = [NSString stringWithFormat:(useChinese ? @"%ld秒前":@"%ld secs ago"), (long)dis];
            break;
        }
        if (dis>=1*60 && dis<=1*60*60-1) {
            result = [NSString stringWithFormat:(useChinese ? @"%ld分钟前":@"%ld mins ago"), (long)dis/60];
            break;
        }
        if (dis>=1*60*60 && dis<=24*60*60-1) {
            result = [NSString stringWithFormat:(useChinese ? @"%ld小时前":@"%ld hours ago"), (long)dis/60/60];
            break;
        }
        if (dis>=24*60*60 && dis<=2*24*60*60-1) {
            result = (useChinese ? @"昨天":@"yesterday");
            break;
        }
        if (dis>=2*24*60*60 && dis<=7*24*60*60-1) {
            result = [NSString stringWithFormat:(useChinese ? @"%ld天前":@"%ld days ago"), (long)dis/24/60/60];
            break;
        }
        if (dis>=7*24*60*60 && dis<=28*24*60*60) {
            result = [NSString stringWithFormat:(useChinese ? @"%ld 星期前":@"%ld weeks ago"), (long)dis/24/60/60/7];
            break;
        }
        
        NSDateFormatter *dfmt = [[NSDateFormatter alloc] init];
        if (useChinese) {
            [dfmt setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hans"]];
        }
        NSString *strFmt = nil;
        if (useChinese) {
            strFmt = (containTime ? @"yyyy-MM-dd HH:mm:ss":@"yyyy-MM-dd");
        }
        else {
            strFmt = (containTime ? @"HH:mm:ss MMM dd, yyyy":@"MMM dd, yyyy");
        }
        [dfmt setDateFormat:strFmt];
        result = [dfmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
        break;
    }
    
    return result;
}
@end
